package com.thinvent.nj.ais.shiro;

import com.thinvent.nj.common.util.WebContextUtil;
import com.thinvent.nj.ais.entity.Resource;
import com.thinvent.nj.ais.entity.Role;
import com.thinvent.nj.ais.entity.User;
import com.thinvent.nj.ais.service.ServerService;
import com.thinvent.nj.ais.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

/**
 * 自定义realm
 * @author liupeijun
 */
public class MyCasRealm extends CasRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private ServerService serverService;

    /**
     *  验证当前登录的用户，获取认证信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        AuthenticationInfo authc = super.doGetAuthenticationInfo(authenticationToken);

        String username = (String) authc.getPrincipals().getPrimaryPrincipal();


        HttpServletRequest request = WebContextUtil.getRequest();

        String ipAddress = request.getScheme() + "://" + request.getLocalAddr();

        if (request.getLocalPort() == 80) {
            ipAddress += request.getContextPath();
        } else {
            ipAddress += ":" + request.getLocalPort() + request.getContextPath();
        }

        String serverName = serverService.getServerNameByUri(ipAddress);
        SecurityUtils.getSubject().getSession().setAttribute("serverName", serverName);


        User user = userService.findByUsername(username, ipAddress);
        SecurityUtils.getSubject().getSession().setAttribute("user", user);

        return authc;
    }


    /**
     * 为当前登录成功的用户授予角色和权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = UserContextUtil.currentUser();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(user.getRoleList().stream().map(Role :: getCode).collect(Collectors.toSet()));
        authorizationInfo.setStringPermissions(user.getResourceList().stream().map(Resource:: getPermission).filter(w -> w != null && !"".equals(w)).collect(Collectors.toSet()));

        return authorizationInfo;
    }


}
